package com.cqh.recruit.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.Key;
import java.util.Date;
import java.util.Map;

public class JwtUtils {

    private static final String SECRET_STRING = "recruit";
    private static Key signKey;
    
    static {
        try {
            // 使用SHA-256哈希算法从"recruit"生成32字节的密钥
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] hashBytes = digest.digest(SECRET_STRING.getBytes(StandardCharsets.UTF_8));
            signKey = new SecretKeySpec(hashBytes, SignatureAlgorithm.HS256.getJcaName());
        } catch (NoSuchAlgorithmException e) {
            // 如果SHA-256不可用，则使用填充方式
            byte[] keyBytes = new byte[32];
            byte[] secretBytes = SECRET_STRING.getBytes(StandardCharsets.UTF_8);
            
            // 重复填充密钥字节直到32字节
            for (int i = 0; i < 32; i++) {
                keyBytes[i] = secretBytes[i % secretBytes.length];
            }
            
            signKey = new SecretKeySpec(keyBytes, SignatureAlgorithm.HS256.getJcaName());
        }
    }
    private static Long expire = 43200000L;

    /**
     * 生成JWT令牌
     * @param claims JWT负载内容
     * @return 生成的JWT令牌
     */
    public static String generateToken(Map<String,Object> claims){
        String jwt = Jwts.builder()
                .addClaims(claims)//添加自定义属性
                .signWith(signKey, SignatureAlgorithm.HS256)//签名算法和密钥
                .setExpiration(new Date(System.currentTimeMillis() + expire))//设置令牌过期时间
                .compact();
        return jwt;
    }

    /**
     * 解析JWT令牌
     * @param token JWT令牌
     * @return JWT第二部分负载 payload 中存储的内容
     */
    public static Claims parseToken(String token){
        Claims claims = Jwts.parserBuilder()
                .setSigningKey(signKey)//密钥
                .build()
                .parseClaimsJws(token)//解析令牌
                .getBody();
        return claims;
    }
}